//
//  PKRequestManager.m
//  Pianke
//
//  Created by lanou on 15/12/22.
//  Copyright © 2015年 Huang. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager

+ (void)requestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic method:(RequestType)method finish:(Finish)finish error:(Error)error {
    // url字符串转化为url对象
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    // 用url对象初始化请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 判断请求方式是否为POST请求,否则默认为GET(GET不用设置请求体)
    if (method == POST) {
        // 设置请求方式
        [request setHTTPMethod:@"POST"];
        // 判断字典中是否有键值对
        if (parDic.count != 0) {
            // 初始化一个字典用来后面保存格式化的字符串键值对
            NSMutableArray *strArray = [NSMutableArray array];
            // 遍历字典
            for (NSString *key in parDic) {
                // 以key=value形式存储键值对于数组中
                NSString *str = [NSString stringWithFormat:@"%@=%@",key,parDic[key]];
                [strArray addObject:str];
            }
            // 所有数组中的元素一次性以某个字符串拼接成另一个字符串
            NSString *parString = [[strArray componentsJoinedByString:@"&"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            // 设置请求体
            [request setHTTPBody:[parString dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    
    // 请求数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (nil == connectionError) {// 请求成功后block调用
            SZLog(@"请求成功");
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            finish(dataDic);// 直接返回字典
        } else {// 请求失败后block调用
            SZLog(@"请求失败");
            error(connectionError);
        }
    }];
}

@end
